package zhcms.framework;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import zhcms.tool.GyMd5;

public class GyCache {
	
	public String cacheRoot= "./cache/";
	//缓存更新时间秒数，0为不缓存
	public long cacheLimitTime= 30;
	  //缓存文件名
  public String cacheFileName= "";
	  //缓存扩展名
	public String cacheFileExt= "htm";
	 //输出的文件内容
	public String cacheReturnS="";
	 //输入的文件内容
	public String cacheGetS="";
	//返回状态,n代表新建，u代表更新，f代表不变
	public String cacheGetZ="";
	//完整的文件名
	private String cacheFileNamePath="";
	
	public boolean cacheIs=true;
	
	public GyCache(long cacheLimitTime,String cacheFileName)
	{
		this.cacheFileName=cacheFileName;
		this.cacheLimitTime=cacheLimitTime;
		this.cacheReturnS="";
		this.cacheGetZ="f";
		this.cacheFileNamePath="";
		//cacheCheck();
	}
	
	public void cacheCheck(String classPath){
		//检查文件是否存在，不存在则不用创建
		
		//获取当前系统的根目录
		//String classPath=Class.class.getClass().getResource("/").getPath();
		//GyReplace r=new GyReplace();
		//classPath=r.replace(classPath, "WEB-INF/classes/", "");
		//System.out.println(classPath);
		//File cachePath=new File(classPath+"/cache");
		createDir(classPath+"/cache");
		//按照当前文件名的md编码生成子文件夹，
		String cFileName=new GyMd5().MD5Encode(this.cacheFileName);
		//System.out.println(cFileName);
		//第一层子文件夹
		createDir(classPath+"/cache/"+cFileName.substring(0,1));
		//第二层子文件夹
		createDir(classPath+"/cache/"+cFileName.substring(0,1)+"/"+cFileName.substring(1,2));
		this.cacheFileNamePath=classPath+"/cache/"+cFileName.substring(0,1)+"/"+cFileName.substring(1,2)+"/"+cFileName+"."+cacheFileExt;
		//检查文件是否存在
		//System.out.println(this.cacheFileNamePath);
		File file=new File(this.cacheFileNamePath);  
		if(!file.exists())  
	    { 
			//如果文件不存在
			this.cacheGetZ="n";
	    }
		else
		{
			//如果文件存在
			boolean filew=getModifiedTime(this.cacheFileNamePath);
			if(filew==true)
			{
				//需要重新写
				//先删除文件，然后重新建立文件
				this.cacheGetZ="u";
			}
			else
			{
				//不需要重新写
				//读取已经存在的
				this.cacheGetZ="f";
			}
		}
	}
	
	private void createDir(String dirName)
	{
		//System.out.println(dirName);
		File cachePath=new File(dirName);
		//如果文件夹不存在则创建  
		if(!cachePath.exists()  && !cachePath.isDirectory())    
		{     
		   cachePath.mkdir();  
		}
		else 
		{
		}
	}
	
	public boolean getModifiedTime(String fileName){  
		boolean r=false;
   File f = new File(fileName);              
   long time = f.lastModified();
   java.util.Date dt = new Date();
   long cTime=dt.getTime();
   
   long chatime=(cTime-time)/1000;
   //System.out.println("修改时间1 " + chatime);     
   //System.out.println("修改时间2 " +cacheLimitTime); 
   if(chatime > cacheLimitTime)
		  {
	   r=true;
		  }
   else
		  {
	   r=false;
		  }
   //System.out.println("修改时间1 " + time);     
   //SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");         
   //cal.setTimeInMillis(time);    
   //System.out.println("修改时间2 " + formatter.format(cal.getTime()));     
        //输出：修改时间[2]    2009-08-17 10:32:38  
   return r;
    } 
	
	public void getContent()
	{
			//读取现有的文件
			File f = new File(this.cacheFileNamePath);
			String content = "";

			List<String> lines = new ArrayList<String>();
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
				String line = null;
				while ((line = br.readLine()) != null) {
					lines.add(line);
				}
				br.close();
			} catch (IOException e) {

			}

			if (lines.size() > 0) {
				for (int i = 0; i < lines.size(); i++) {
					content = content + lines.get(i).toString() + "\n";
				}
			}
		this.cacheReturnS=content;
	}
	
	public void getContent(String iCharset)
	{
			//读取现有的文件
			File f = new File(this.cacheFileNamePath);
			//String content = "";
			StringBuilder strContent = new StringBuilder("");
			List<String> lines = new ArrayList<String>();
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f), iCharset));
				String line = null;
				while ((line = br.readLine()) != null) {
					lines.add(line);
				}
				br.close();
			} catch (IOException e) {

			}

			if (lines.size() > 0) {
				for (int i = 0; i < lines.size(); i++) {
					//content = content + lines.get(i).toString() + "\n";
					strContent.append(lines.get(i).toString());
					strContent.append("\n");
				}
			}
			this.cacheReturnS=strContent.toString();	
			strContent=null;
		//this.cacheReturnS=content;
	}
	
	
	public void WriteNewFile(String ifilecontent)
	{
		File file=new File(this.cacheFileNamePath); 
		try {  
	        file.createNewFile();
	        			//写入文件内容
	        FileWriter fw = null; 
	        fw = new FileWriter(this.cacheFileNamePath);  
	        fw.write(ifilecontent);
	        fw.close();
	        this.cacheReturnS=ifilecontent;
	     } catch (IOException e) {  
	       e.printStackTrace();  
	        }  
	}
	
	public void WriteUpdateFile(String ifilecontent)
	{
		File file=new File(this.cacheFileNamePath); 
		try {  
	        file.delete();
	        			//写入文件内容
	        FileWriter fw = null; 
	        fw = new FileWriter(this.cacheFileNamePath);  
	        fw.write(ifilecontent);
	        fw.close();
	        this.cacheReturnS=ifilecontent;
	     } catch (IOException e) {
	       e.printStackTrace();  
	        }  
	}
	
	public void WriteNewFile(String ifilecontent,String iCharset)
	{
		if(iCharset.equals("UTF-8"))
		{
			String path=this.cacheFileNamePath;
	        try {
	            OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(path),"UTF-8");
	            out.write(ifilecontent);
	            out.flush();
	            out.close();
	            //System.out.println("success...");
	        } catch (UnsupportedEncodingException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } catch (FileNotFoundException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } catch (IOException e){
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }

		}
		else
		{
			File file=new File(this.cacheFileNamePath); 
			try {  
		        file.createNewFile();
		        			//写入文件内容
		        FileWriter fw = null; 
		        fw = new FileWriter(this.cacheFileNamePath);  
		        fw.write(ifilecontent);
		        fw.close();
		        this.cacheReturnS=ifilecontent;
		     } catch (IOException e) {  
		       e.printStackTrace();  
		     }  
		}

	}
	
	public void WriteUpdateFile(String ifilecontent,String iCharset)
	{
		if(iCharset.equals("UTF-8"))
		{
			File file=new File(this.cacheFileNamePath); 
		    file.delete();
		    file=null;
		    String path=this.cacheFileNamePath;
	        try {
	            OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(path),"UTF-8");
	            out.write(ifilecontent);
	            out.flush();
	            out.close();
	        } catch (UnsupportedEncodingException e) {
	            e.printStackTrace();
	        } catch (FileNotFoundException e) {
	            e.printStackTrace();
	        } catch (IOException e){
	            e.printStackTrace();
	        }
		    
		}
		else
		{
			File file=new File(this.cacheFileNamePath); 
			try {  
		        file.delete();
		        			//写入文件内容
		        FileWriter fw = null; 
		        fw = new FileWriter(this.cacheFileNamePath);  
		        fw.write(ifilecontent);
		        fw.close();
		        this.cacheReturnS=ifilecontent;
		     } catch (IOException e) {
		       e.printStackTrace();  
		     }  
		}
		
	}
	
	public String getCacheGetZ()
	{
		return this.cacheGetZ;
	}
	
	public String getCacheReturnS()
	{
		return this.cacheReturnS;
	}
	
}
